package com.l.web;

import com.l.domain.User;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * author: 甘叶勇
 * date:  2016/6/17 18:21.
 */
@RestController
@RequestMapping("/users")
public class UserController {
    // 创建线程安全的Map
    private static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());
    private static final String SUCCESS = "success";

    @RequestMapping("/")
    public List<User> list() {
        return new ArrayList<User>(users.values());
    }

    @RequestMapping(value = "/", method = RequestMethod.POST)
    public String post(User user) {
        users.put(user.getId(), user);

        return SUCCESS;
    }

    @RequestMapping("/{id}")
    public User get(@PathVariable Long id) {
        return users.get(id);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    public String put(@PathVariable Long id, User user) {
        User u = users.get(id);
        u.setName(user.getName());
        u.setAge(user.getAge());
        users.put(id, u);

        return SUCCESS;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public String delete(@PathVariable Long id) {
        users.remove(id);

        return SUCCESS;
    }
}
